﻿
using Newtonsoft.Json;
using PivotData.Json;
using System;
using System.Linq;

namespace PivotData
{
    /// <summary>
    /// Basic interface for a facet (of data)
    /// </summary>
    /// <remarks>
    /// Based on the info found here: http://msdn.microsoft.com/en-us/library/hh425591(v=vs.95).aspx
    /// </remarks>
    [Serializable]
    [JsonConverter(typeof(FacetAbsBaseJsonConverter))]
    public abstract class FacetAbsBase
    {
        /// <summary>
        /// Name of the facet
        /// </summary>
        [JsonProperty]
        public string Name;
    }

    /// <summary>
    /// Convert from JSON.
    /// </summary>
    internal class FacetAbsBaseJsonConverter : JsonCreationConverter<FacetAbsBase>
    {
        protected override FacetAbsBase Create(Type objectType, Newtonsoft.Json.Linq.JObject jObject)
        {
            if (jObject.Properties().Where(p => p.Name == "Value").Any())
                return new FacetString();

            if (jObject.Properties().Where(p => p.Name == "Number").Any())
                return new FacetNumber();

            if (jObject.Properties().Where(p => p.Name == "Date").Any())
                return new FacetDateTime();

            if (jObject.Properties().Where(p => p.Name == "LinkString").Any())
                return new FacetUri();

            //
            // Uh oh, no clude what happened here!
            //

            throw new InvalidOperationException();
        }
    }
}
